package com.vivi.yy;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.MaxReward;
import com.applovin.mediation.MaxRewardedAdListener;
import com.applovin.mediation.ads.MaxRewardedAd;
import com.applovin.sdk.AppLovinMediationProvider;
import com.applovin.sdk.AppLovinPrivacySettings;
import com.applovin.sdk.AppLovinSdk;
import com.applovin.sdk.AppLovinSdkInitializationConfiguration;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.security.MessageDigest;

public class VWSDKManager implements Application.ActivityLifecycleCallbacks ,MaxRewardedAdListener{

    public static final String MAX_KEY = "vs2AMKt7Y+7Lyz2SqC4Uyi8uzrZuNFNueQuzXsW/Hi6Mrbx9mXNwisnQG4C4Bw+dSk6auGEPdhcaFfdn6slRDcGQqiSlXnj4k+kejZFwDtlfEcHAW3U=";
    public static final String REWARD_PLACEMENTID = "94f26e0a2fab987b";
    public static final String GAME_MAIN_CLS = "org.cocos2dx.javascript.AppActivity";
    public static final String LIB_PATH="org.cocos2dx.lib";

    public static WeakReference<Activity> mainGameActivity;
    private static Method evalString;
    private static Method runOnGLThread;
    public static Context mApplication;

    private static MaxRewardedAd maxRewardedAd;
    private static String mAdSource="";

    public static VWSDKManager getVWSDKManager() {
        return InstanceHolder.GAME_APPLICATION;
    }

    @Override
    public void onUserRewarded(@NonNull MaxAd maxAd, @NonNull MaxReward maxReward) {

    }

    @Override
    public void onAdLoaded(@NonNull MaxAd maxAd) {

    }

    @Override
    public void onAdDisplayed(@NonNull MaxAd maxAd) {

    }

    @Override
    public void onAdHidden(@NonNull MaxAd maxAd) {
        maxRewardedAd.loadAd();
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ad_source", mAdSource);
            videoCallback("ad_over_vivid", jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAdClicked(@NonNull MaxAd maxAd) {

    }

    @Override
    public void onAdLoadFailed(@NonNull String s, @NonNull MaxError maxError) {

    }

    @Override
    public void onAdDisplayFailed(@NonNull MaxAd maxAd, @NonNull MaxError maxError) {
        callbackAdError();
    }

    private static class InstanceHolder {
        private static final VWSDKManager GAME_APPLICATION = new VWSDKManager();
    }

    public void init(Activity activity) {
        mApplication = activity.getApplicationContext();
        ((Application) mApplication).registerActivityLifecycleCallbacks(this);

        AppLovinPrivacySettings.setHasUserConsent(true);
        AppLovinPrivacySettings.setDoNotSell(false);
        init(mApplication);

    }

    private void init(Context mApplication) {
        AppLovinSdk.getInstance(mApplication).initialize(getInitConfig(), config -> {
//                AppLovinSdk.getInstance(context).showMediationDebugger();
            loadRewardAd(mApplication);
        });
    }

    private AppLovinSdkInitializationConfiguration getInitConfig() {
        return AppLovinSdkInitializationConfiguration.builder(decrypt(MAX_KEY))
                .setMediationProvider(AppLovinMediationProvider.MAX)
                .build();
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        try {
            onActivityCreated(activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void onActivityCreated(Activity activity) {
        if (activity.getClass().getName().equals(GAME_MAIN_CLS)) {
            setMainGameActivity(activity);
        }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);
        getRunOnGLThread();
        getEvalString();
    }

    private void getEvalString() {
        try {
            Class<?> clzBridge = Class.forName(LIB_PATH.concat(".Cocos2dxJavascriptJavaBridge"), false, mApplication.getClassLoader());
            evalString = clzBridge.getDeclaredMethod("evalString", String.class);
            evalString.setAccessible(true);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static final Handler handler = new Handler(Looper.getMainLooper());

    public void videoCallback(String action, String jsonData) {
        if (mainGameActivity == null || mainGameActivity.get() == null ) {
            return;
        }
        runOnGLThreadInvoke(action,jsonData);
    }

    private void runOnGLThreadInvoke(String action, String jsonData) {
        handler.post(() -> {
            try {
                runOnGLThread.invoke(mainGameActivity.get(), (Runnable) () -> callback(action, jsonData));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void getRunOnGLThread() {
        try {
            Class<?> clzCocos2dAct = Class.forName(LIB_PATH.concat(".Cocos2dxActivity"), false, mApplication.getClassLoader());
            runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread", Runnable.class);
            runOnGLThread.setAccessible(true);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void callback(String action, String jsonData) {
        try {
            evalString.invoke(null, String.format("window.VividCallback('%s','%s')", action, jsonData));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showToast(final String message) {
        if (mainGameActivity == null || mainGameActivity.get() == null) {
            return;
        }
        Activity activity =mainGameActivity.get();
        activity.runOnUiThread(() -> Toast.makeText(activity, message, Toast.LENGTH_SHORT).show());
    }

    public void playAd(String adSource){
        if (mainGameActivity == null || mainGameActivity.get() == null) {
            return;
        }
        showAd(mainGameActivity.get(), adSource);
    }


    public void loadRewardAd(Context context) {
        maxRewardedAd =MaxRewardedAd.getInstance(REWARD_PLACEMENTID);
        maxRewardedAd.setListener(this);
        maxRewardedAd.loadAd();
    }

    public void showAd(Activity activity, String adSource) {
        if (check()){
            setAdSource(adSource);
            show(activity);
        }
    }

    private boolean check() {
        if (maxRewardedAd==null || !maxRewardedAd.isReady()) {
            callbackAdError();
            maxRewardedAd.loadAd();
            return false;
        }
        return true;
    }

    private void show(Activity activity) {
        if (maxRewardedAd!=null) {
            maxRewardedAd.showAd(activity);
        }
    }

    private void setAdSource(String adSource) {
        if (adSource!=null){
            mAdSource = adSource;
        }
    }

    public void callbackAdError() {
        videoCallback("ad_error_vivid", "{}");
    }

    private static final String SECRET_KEY = "dwR212rTs23sdTs2";
//    public static String encrypt(String plainText) {
//        try {
//            // 使用SHA-256派生密钥
//            MessageDigest digest = MessageDigest.getInstance("SHA-256");
//            byte[] key = digest.digest(SECRET_KEY.getBytes("UTF-8"));
//
//            // 简单块加密
//            byte[] textBytes = plainText.getBytes("UTF-8");
//            byte[] encrypted = new byte[textBytes.length];
//
//            for (int i = 0; i < textBytes.length; i++) {
//                encrypted[i] = (byte) (textBytes[i] ^ key[i % key.length]);
//            }
//
//            return Base64.encodeToString(encrypted, Base64.NO_WRAP);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "";
//        }
//    }

    public String decrypt(String encryptedText) {
        try {
            // 使用SHA-256派生密钥（与加密相同）
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] key = digest.digest(SECRET_KEY.getBytes("UTF-8"));

            // Base64解码
            byte[] encryptedBytes = Base64.decode(encryptedText, Base64.NO_WRAP);
            byte[] decrypted = new byte[encryptedBytes.length];

            // 逆向XOR操作（解密）
            for (int i = 0; i < encryptedBytes.length; i++) {
                decrypted[i] = (byte) (encryptedBytes[i] ^ key[i % key.length]);
            }

            return new String(decrypted,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
